package com.xfgg.cloud.adapter;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.xfgg.cloud.adapter.request.LoginRequest;
import com.xfgg.cloud.app.AuthService;
import com.xfgg.cloud.app.ElasticSearchService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限认证框架两种方式
 * 1、Session认证
 * 2、Token认证 这里主要实现这个
 * 详情可见：文章
 *
 * @author xfgg
 */
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AuthController {
    private final AuthService authService;
    private final ElasticSearchService elasticSearchService;

    @SentinelResource("login")
    @PostMapping("/login")
    public ResponseEntity<Void> login(@RequestBody LoginRequest loginRequest) {
        //生成token
        String token = authService.createToken(loginRequest);
        //记录请求日志
        elasticSearchService.loginLog(loginRequest);
        //header带上token返回
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization", token);
        return new ResponseEntity<>(httpHeaders, HttpStatus.OK);
    }

    @GetMapping("/logout")
    public ResponseEntity<Void> logOut() {
        authService.removeToken();
        return new ResponseEntity<>(HttpStatus.OK);
    }

    public static void main(String[] args) {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("login");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(20);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
        while (true) {
            try (Entry entry = SphU.entry("login")){
                // 被保护的逻辑
                System.out.println("hello world");
            }catch (BlockException ex){
                // 处理被流控的逻辑
                System.out.println("blocked!");
            }
        }
    }
}
